# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/11 18:46 
@Author  : ZhangShenao 
@File    : worker.py 
@Desc    : 异步工作worker模式

协程是单线程,并且由用户决定什么时候执行,和在哪些地方交出控制权,切换到下一个任务
"""
import asyncio

from bacis.decorator.perf_log_decorator import perf_log


async def worker1():
    """worker1 coroutine"""

    # 事件调度器开始调度worker1,worker1开始执行
    print('worker1 start')

    # worker1交出事件调度器的控制权,调度器开始调度执行asyncio.sleep
    await asyncio.sleep(1)

    # sleep执行完成,worker重新获得事件调度器的控制权,继续执行
    print('worker1 end')


async def worker2():
    """worker2 coroutine"""
    print('worker2 start')
    await asyncio.sleep(1)
    print('worker2 end')


async def main():
    # 创建异步任务,并进入事件循环等待运行
    task1 = asyncio.create_task(worker1())
    task2 = asyncio.create_task(worker2())
    print('before await')

    # 用户主动选择从当前的主Coroutine中切出,事件调度器开始调度worker1
    await task1
    # task1执行完成,主Coroutine重新获取事件调度器的控制权,继续执行
    print('awaited worker1')

    # 事件调度器开始调度worker2
    await task2
    print('awaited worker2')


@perf_log
def run():
    """执行函数"""

    # 使用asyncio.run()函数,开启事件循环
    asyncio.run(main())


run()
